import {AUTH_FAILURE, AUTH_LOGOUT, AUTH_SUCCESS, START_SPINNER, STOP_SPINNER} from "./actionTypes";

export const startSpinner = () => ({type: START_SPINNER});

export const stopSpinner = () => ({type: STOP_SPINNER});

export const authSuccess = (token) => ({type: AUTH_SUCCESS, token: token});

export const authFailure = () => ({type: AUTH_FAILURE});

export const authLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('expirationTime');
    return {type: AUTH_LOGOUT};
};

export const authCheckState = () => (dispatch => {
    const token = localStorage.getItem('token');
    if (!token) {
        dispatch(authLogout());
    } else {
        const expirationTime = new Date(localStorage.getItem('expirationTime'));
        if (expirationTime <= new Date()) {
            dispatch(authLogout());
        } else {
            dispatch(authSuccess(token));
            dispatch(checkAuthTimeout((expirationTime.getTime() - new Date().getTime()) / 1000 ));
        }
    }
});

export const checkAuthTimeout = (expirationTime) => (dispatch => {
    setTimeout(() => dispatch(authLogout()), expirationTime * 1000);
});